package com.jp.refreshlocalcacheserver.aspect;

import com.jp.refreshlocalcacheserver.annotation.RefreshLocalCachePoint;
import com.jp.refreshlocalcacheserver.net.netty.response.RefresResponseMsg;
import com.jp.refreshlocalcacheserver.net.netty.session.ActiveSessionRegistry;
import com.jp.refreshlocalcacheserver.net.netty.session.SessionData;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: jipeng
 * @Description:
 * @Date: Created in 2020/5/19 10:40
 */
@Aspect
@Component
public class RefreshLocalCacheAspect {
    private Logger logger = LoggerFactory.getLogger(this.getClass());



    @Pointcut(value = "@annotation(com.jp.refreshlocalcacheserver.annotation.RefreshLocalCachePoint)")
    public void refreshLocalCache(){ }

    @Around("refreshLocalCache() && @annotation(refreshLocalCachePoint)")
    public void doAround(ProceedingJoinPoint pjp, RefreshLocalCachePoint refreshLocalCachePoint) throws Throwable {
        pjp.proceed();

        String cacheKey = refreshLocalCachePoint.cacheKey();

        System.out.println("cacheKey => " + cacheKey);
        try{
            //发送同步通知
            List<Integer> channelIds = ActiveSessionRegistry.getChannelIdByCacheKey(cacheKey);
            if(channelIds == null){
                return;
            }
            SessionData sessionData;
            for(Integer channleId : channelIds){
                 sessionData =  ActiveSessionRegistry.getSessionData(channleId);
                 if(sessionData == null){
                     continue;
                 }

                 new RefresResponseMsg(cacheKey).sendTo(sessionData.getContext());
            }
        }catch (Exception e){
            logger.error("send {} Sync notify，error => {}", cacheKey, ExceptionUtils.getStackTrace(e));
        }
    }






}
